package com.xinongbest.proxy;

import com.xinongbest.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author lemonwan
 * 动态代理:事务控制
 */
public class DynamicProxy {

//    private static final DynamicProxy dynamicProxy = new DynamicProxy();
//
//    private DynamicProxy() {
//
//    }
//
//    public static DynamicProxy getInstance() {
//        return  dynamicProxy;
//    }

    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * 使用JDK动态代理生成代理对象：代理接口
     *
     * @param object 被代理对象
     * @return 代理对象
     */
    public Object getJdkProxyObject(Object object) {
        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object invoke = null;
                try {
                    transactionManager.startTransaction();
                    invoke = method.invoke(object, args);
                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    transactionManager.rollback();
                }
                return invoke;
            }
        });
    }

    /**
     * 使用CGLIB代理生成代理对象：代理对象（注意：CGLIB也可以代理接口）
     *
     * @param obj 被代理对象
     * @return 代理对象
     */
    public Object getCglibProxyObject(Object obj) {
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object invoke = null;
                try {
                    transactionManager.startTransaction();
                    invoke = method.invoke(obj, objects);
                    transactionManager.commit();
                } catch (Exception e) {
                    transactionManager.rollback();
                }
                return invoke;
            }
        });
    }

}
